<template>
  <div class="hotel-detail">
    <div class="hotel-header">
      <h1 class="hotel-title">{{ detail.chineseName || detail.name }}</h1>
      <div class="hotel-address" v-if="detail.address">
        <i class="el-icon-location-outline"></i> {{ detail.address }}
      </div>
    </div>
    <!-- 轮播图 -->
    <el-card class="carousel-card" shadow="hover">
      <el-carousel v-if="imgList.length" height="340px" indicator-position="outside">
        <el-carousel-item v-for="(img, idx) in imgList" :key="idx">
          <img :src="img" class="carousel-img" />
        </el-carousel-item>
      </el-carousel>
    </el-card>
    <!-- 酒店价格和预定按钮 -->
    <div class="hotel-price-row">
      <span class="hotel-detail-price">￥{{ detail.lowestPrice }} <span class="qi">起</span></span>
      <el-button type="warning" size="large" class="order-btn" @click="showDatePicker = true">立即预定</el-button>
    </div>
    <!-- 酒店床型查询区域 -->
    <el-card class="bedtype-card" shadow="hover">
      <h3 class="bedtype-title">可选床型</h3>
      <div v-if="rooms.length === 0" class="bedtype-empty">暂无床型信息</div>
      <div v-else class="bedtype-list">
        <div v-for="room in rooms" :key="room.roomId" class="bedtype-item">
          <img v-if="room.pics" :src="room.pics" class="bedtype-img" />
          <div class="bedtype-info">
            <div class="bedtype-name">{{ room.bedTypeName }}</div>
            <div class="bedtype-desc">{{ room.roomName }}</div>
            <div class="bedtype-desc">价格：￥{{ room.price }}</div>
          </div>
          <el-button type="primary" size="small" style="margin-left: 18px;" @click="showRoomDetail(room)">立即预定</el-button>
        </div>
      </div>
    </el-card>
    <!-- 酒店名称、星级、商圈 -->
    <div class="hotel-brief hotel-brief-separated">
      <span class="hotel-brief-title">{{ detail.chineseName || detail.name }}</span>
      <span v-if="detail.starName" class="hotel-brief-star">{{ detail.starName }}</span>
      <span v-if="detail.business" class="hotel-brief-biz">{{ detail.business }}</span>
      <span v-if="detail.score !== undefined && detail.score !== null" class="hotel-brief-score">评分 {{ detail.score }}</span>
      <span v-if="detail.scoreDesc" class="hotel-brief-score-desc">{{ detail.scoreDesc }}</span>
    </div>

    <!-- 简介 -->
    <el-card class="section" shadow="hover">
      <h2 class="section-title">酒店简介</h2>
      <div class="section-content" v-html="detail.info"></div>
    </el-card>

    <!-- 入住须知 -->
    <el-card class="section" shadow="hover">
      <h2 class="section-title">入住须知</h2>
      <ul v-if="Array.isArray(detail.policies)" class="policy-list">
        <li v-for="(item, idx) in detail.policies" :key="idx">
          <span class="policy-label">{{ item.label }}</span>
          <span class="policy-text">{{ item.text }}</span>
        </li>
      </ul>
      <div v-else v-html="detail.policies"></div>
    </el-card>

    <!-- 地图 -->
    <el-card class="section" shadow="hover">
      <h2 class="section-title">酒店位置</h2>
      <div id="hotel-map" class="hotel-map"></div>
    </el-card>

    <el-dialog v-model="showDatePicker" title="选择入住和离店日期" width="340px" :close-on-click-modal="false" :show-close="true">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="入住日期"
        end-placeholder="离店日期"
        :disabled-date="disabledBeforeToday"
        style="width: 100%"
      />
      <template #footer>
        <el-button @click="showDatePicker = false">取消</el-button>
        <el-button type="primary" @click="onDateConfirm">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showRoomDialog" title="床型详情" width="420px">
      <div v-if="selectedRoom">
        <!-- 支持多图轮播，兼容pics为数组或字符串，也兼容pic字段 -->
        <div v-if="selectedRoom.pics">
          <el-carousel v-if="Array.isArray(selectedRoom.pics)" height="140px" indicator-position="outside">
            <el-carousel-item v-for="(img, idx) in selectedRoom.pics" :key="idx">
              <img :src="img" style="width:100%;height:140px;object-fit:cover;border-radius:8px;margin-bottom:12px;" />
            </el-carousel-item>
          </el-carousel>
          <img v-else :src="selectedRoom.pics" style="width:100%;height:140px;object-fit:cover;border-radius:8px;margin-bottom:12px;" />
        </div>
        <img v-else-if="selectedRoom.pic" :src="selectedRoom.pic" style="width:100%;height:140px;object-fit:cover;border-radius:8px;margin-bottom:12px;" />
        <div style="font-weight:bold;font-size:1.1rem;margin-bottom:6px;">{{ selectedRoom.bedTypeName }} - {{ selectedRoom.roomName }}</div>
        <div style="color:#888;margin-bottom:8px;">价格：￥{{ selectedRoom.price }}</div>
        <div style="color:#888;margin-bottom:8px;">楼层：{{ selectedRoom.floor || '无' }}，窗户：{{ selectedRoom.window || '无' }}</div>
        <div style="color:#888;margin-bottom:8px;">面积：{{ selectedRoom.area || '无' }}</div>
        <el-form label-width="80px">
          <el-form-item label="入住日期">
            <el-date-picker v-model="selectedDate" type="daterange" range-separator="至" start-placeholder="入住日期" end-placeholder="离店日期" style="width: 100%" :disabled-date="disabledBeforeToday" />
          </el-form-item>
          <el-form-item label="入住人信息">
            <el-select v-model="guestInfo" placeholder="请选择入住人">
              <el-option v-for="item in guestList" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div style="flex:1;text-align:left;color:#fa541c;font-weight:bold;" v-if="selectedRoom && selectedDate && selectedDate.length === 2">
          总价：￥{{ selectedRoom.price * ((new Date(selectedDate[1]) - new Date(selectedDate[0]))/(1000*60*60*24)) }}
          <span style="color:#888;font-weight:normal;font-size:13px;">（￥{{ selectedRoom.price }} × {{ (new Date(selectedDate[1]) - new Date(selectedDate[0]))/(1000*60*60*24) }}晚）</span>
        </div>
        <el-button @click="showRoomDialog = false">关闭</el-button>
        <el-button type="primary" @click="confirmRoom">确定下单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import { ElDialog, ElDatePicker, ElButton, ElMessage, ElInput } from 'element-plus'

const route = useRoute()
const detail = ref({})
const imgList = ref([])
const showDatePicker = ref(false)
const dateRange = ref([])
const rooms = ref([])

// 查询当前酒店床型
async function fetchBedTypes() {
  const hotelId = detail.value.id || route.params.id
  try {
    const { data } = await axios.post(`/Hotel/detail/${hotelId}`)
    // bedTypes.value = data || [] // This line is no longer needed as rooms is used
  } catch (e) {
    // bedTypes.value = [] // This line is no longer needed
  }
}

onMounted(async () => {
  // 先查酒店详情
  const hotelId = route.params.id
  const detailRes = await axios.post(`/Hotel/detail/${hotelId}`)
  detail.value = detailRes.data
  // 再查房型列表
  const roomsRes = await axios.post(`/Hotel/rooms/${hotelId}`)
  rooms.value = roomsRes.data || []
  // 解析 policies 字段为 JSON 数组（如果是 JSON 字符串）
  if (detail.value.policies) {
    try {
      detail.value.policies = JSON.parse(detail.value.policies)
    } catch {
      // 不是 JSON 字符串则保持原样
    }
  }
  // 解析图片字段
  if (detail.value && detail.value.imgs) {
    try {
      imgList.value = JSON.parse(detail.value.imgs)
    } catch {
      imgList.value = detail.value.imgs.split(',')
    }
  }
  // 查询床型
  await fetchBedTypes()

  // 解析经纬度字符串并渲染百度地图
  let lng = null, lat = null
  if (detail.value.location) {
    [lat, lng] = detail.value.location.split(',').map(Number)
  }
  await nextTick()
if (lng && lat && window.BMapGL) {
  const map = new window.BMapGL.Map('hotel-map')
  const point = new window.BMapGL.Point(lng, lat)
  map.centerAndZoom(point, 16)
  map.enableScrollWheelZoom(true)
  const marker = new window.BMapGL.Marker(point)
  map.addOverlay(marker)
  marker.setTitle(detail.value.name || '酒店位置')
}
})

function disabledBeforeToday(date) {
  const today = new Date()
  today.setHours(0,0,0,0)
  return date < today
}
function onDateConfirm() {
  if (dateRange.value && dateRange.value.length === 2) {
    showDatePicker.value = false
    // 这里可以处理选中的日期，比如发起预定请求
    // console.log('预定日期', dateRange.value)
  }
}

function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
function confirmRoom() {
  // 校验入住日期
  if (!selectedDate.value || selectedDate.value.length !== 2) {
    ElMessage.warning('请先选择入住日期后再下单！')
    return
  }
  if (!guestInfo.value || !guestInfo.value.trim()) {
    ElMessage.warning('请填写入住人信息！')
    return
  }
  // 获取弹框中填写的数据
  const checkInDate = formatDate(new Date(selectedDate.value[0])); // 入住日期
  const checkOutDate = formatDate(new Date(selectedDate.value[1])); // 离店日期
  // 计算入住天数和总价
  const nights = Math.ceil((new Date(selectedDate.value[1]) - new Date(selectedDate.value[0])) / (1000 * 60 * 60 * 24));
  const totalAmount = selectedRoom.value.price * nights;
  // 构建发送给后端的数据
  const orderData = {
    hotelId: detail.value.id || route.params.id,
    hotelName: detail.value.chineseName || detail.value.name,
    roomId: selectedRoom.value.roomId,
    roomName: selectedRoom.value.roomName,
    bedTypeName: selectedRoom.value.bedTypeName,
    checkInDate: checkInDate,        // 入住日期
    checkOutDate: checkOutDate,      // 离店日期
    nights: nights,                  // 入住天数
    unitPrice: selectedRoom.value.price,
    totalAmount: totalAmount,
    guestInfo: guestInfo.value
  }
  // 调用后端API创建酒店订单
  axios.post('/HotelPay/addOrder', orderData).then(res => {
    showRoomDialog.value = false
    console.log('下单返回：', res.data)
    const order = res.data
    ElMessage.success({
      message: `订单创建成功！订单号：${order.orderNo}，总金额：￥${totalAmount}`,
      duration: 5000
    })
    // 调用支付接口
    axios.post(`/HotelPay/pay?orderId=${order.orderNo}&money=${totalAmount}`).then(payRes => {
      if (payRes.data) {
        window.open(payRes.data, '_blank', 'width=600,height=600')
      }
    }).catch(err => {
      console.log('支付接口调用失败', err)
    })
  }).catch(err => {
    console.error('创建订单失败:', err)
    ElMessage.error('创建订单失败，请重试')
  })
}

const showRoomDialog = ref(false)
const selectedRoom = ref(null)
const selectedDate = ref([])
const guestInfo = ref('')
const guestList = ref([])
const userId = sessionStorage.getItem('userId')

function showRoomDetail(room) {
  selectedRoom.value = room
  showRoomDialog.value = true
  selectedDate.value = []
  guestInfo.value = ''
  // 获取入住人信息
  axios.post('/residentInfo/list2', {}).then(res => {
    console.log('后端返回:', res.data)
    let arr = Array.isArray(res.data) ? res.data : res.data.data
    if (Array.isArray(arr)) {
      guestList.value = arr.map(item => ({
        id: item.id,
        name: item.name
      }))
    } else {
      guestList.value = []
    }
  })
}
</script>

<style scoped>
.hotel-detail {
  max-width: 900px;
  margin: 0 auto;
  padding: 32px 12px 32px 12px;
  background: #f7f9fb;
}
.carousel-card {
  border-radius: 18px;
  overflow: hidden;
  margin-bottom: 28px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.10);
}
.carousel-img {
  width: 100%;
  height: 340px;
  object-fit: cover;
  display: block;
  border-radius: 18px;
  background: #f5f7fa;
  transition: transform 0.3s;
}
.carousel-img:hover {
  transform: scale(1.03);
}
.hotel-header {
  margin: 24px 0 12px 0;
  text-align: left;
}
.hotel-title {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 6px;
  color: #222;
}
.hotel-address {
  color: #888;
  font-size: 15px;
  display: flex;
  align-items: center;
  gap: 4px;
}
.section {
  margin-top: 28px;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}
.section-title {
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}
.section-content {
  color: #444;
  font-size: 15px;
  line-height: 1.7;
}
.policy-list {
  padding-left: 0;
  list-style: none;
}
.policy-label {
  font-weight: bold;
  color: #1976d2;
  margin-right: 8px;
}
.policy-text {
  color: #555;
}
.hotel-map {
  width: 100%;
  height: 320px;
  border-radius: 12px;
  background: #e3f2fd;
  margin-top: 8px;
}
.hotel-brief {
  margin: 32px 0 0 0;
  display: flex;
  align-items: center;
  gap: 24px;
}
.hotel-brief-title {
  font-size: 1.7rem;
  font-weight: bold;
  color: #222;
}
.hotel-brief-star {
  font-size: 1.15rem;
  color: #fff;
  background: #5c8df6;
  border-radius: 12px;
  padding: 4px 18px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(92,141,246,0.08);
}
.hotel-brief-biz {
  font-size: 1.15rem;
  color: #fff;
  background: #7bc67e;
  border-radius: 12px;
  padding: 4px 18px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(123,198,126,0.08);
}
.hotel-brief-score {
  font-size: 1.15rem;
  color: #fff;
  background: #ffb74d;
  border-radius: 12px;
  padding: 4px 18px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(255,183,77,0.08);
}
.hotel-brief-score-desc {
  font-size: 1.15rem;
  color: #fff;
  background: #b39ddb;
  border-radius: 12px;
  padding: 4px 18px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(179,157,219,0.08);
}
.hotel-brief-separated {
  margin-top: 38px !important;
  margin-bottom: 10px;
}
.hotel-price-row {
  display: flex;
  align-items: center;
  gap: 28px;
  margin: 18px 0 0 0;
  font-size: 1.5rem;
  font-weight: bold;
}
.hotel-detail-price {
  color: #fa541c;
  font-size: 2rem;
  font-weight: bold;
}
.hotel-detail-price .qi {
  font-size: 1rem;
  color: #888;
  margin-left: 2px;
}
.order-btn {
  border-radius: 16px;
  font-size: 1.1rem;
  font-weight: bold;
  padding: 0 22px;
  background: #faad14;
  border: none;
  color: #fff;
  transition: background 0.2s;
}
.order-btn:hover {
  background: #fa541c;
}
.bedtype-card {
  margin-top: 18px;
  border-radius: 14px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.04);
  padding: 18px 12px;
}
.bedtype-title {
  font-size: 1.15rem;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}
.bedtype-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.bedtype-item {
  display: flex;
  align-items: center;
  background: #f8f8f8;
  border-radius: 10px;
  padding: 14px 18px;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 1px 6px rgba(0,0,0,0.04);
}
.bedtype-img {
  width: 100px;
  height: 70px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 18px;
  background: #eee;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.bedtype-info {
  flex: 1;
}
.bedtype-name {
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 4px;
}
.bedtype-desc {
  color: #888;
  font-size: 0.98rem;
  margin-bottom: 2px;
}
.bedtype-empty {
  color: #aaa;
  font-size: 1rem;
  text-align: center;
  margin: 16px 0;
}
</style>